using Godot;
using System;
using System.Collections.Generic;
using System.Linq;

public partial class LevelInfo : Node2D
{
    [Signal]
    public delegate void OnMenuButtonCommandEventHandler(string command);

    [Signal]
    public delegate void OnMenuAnimatedEventHandler();

    [Signal]
    public delegate void OnRobotListItemPressedEventHandler(Robot robot);

    #region 子组件
    Label gameRound;
    Label redNum;
    Label blueNum;
    Button buttonRed;
    Button buttonBlue;
    Button levelMenu;

    Control MenuRoot;
    VBoxContainer buttonsRoot;
    Button backMenu;
    Button saveGame;
    Button loadGame;
    Button endRound;
    Button backLevel;

    FlowContainer messageRoot;

    PanelContainer robotList;
    Label listInfoLabel;
    UIButton closeRobotList;

    VBoxContainer levelRobotList;
    #endregion

    PackedScene robotItemPrefab = ResourceLoader.Load<PackedScene>(Path.LEVEL_ROBOT_LIST_ITEM);
    PackedScene message = ResourceLoader.Load<PackedScene>(Path.WARNING_COMPONENT);

    BaseLevelManager levelManager;
    RobotManager rmg;

    public void Init(BaseLevelManager levelManager)
    {
        this.levelManager = levelManager;
        rmg = levelManager.RobotManager;
    }

    void GetChildComponents()
    {
        levelMenu = GetNode<Button>("%LevelMenu");
        levelMenu.Pressed += LevelMenuPressedHandler;
        gameRound = GetNode<Label>("%GameRound");
        redNum = GetNode<Label>("%RedNum");
        blueNum = GetNode<Label>("%BlueNum");
        buttonRed = GetNode<Button>("%ButtonRed");
        buttonRed.Pressed += ShowEnemyRobotListHandler;
        buttonBlue = GetNode<Button>("%ButtonBlue");
        buttonBlue.Pressed += ShowPlayerRobotListHandler;

        MenuRoot = GetNode<Control>("%MenuRoot");
        buttonsRoot = GetNode<VBoxContainer>("%ButtonsRoot");
        messageRoot = GetNode<FlowContainer>("%MessageRoot");
        foreach (var child in buttonsRoot.GetChildren())
        {
            if (child is UIButton b)
            {
                b.OnPressed += OnButtonPressedHandler;
            }
        }

        robotList = GetNode<PanelContainer>("%RobotList");
        listInfoLabel = GetNode<Label>("%ListInfoLabel");
        closeRobotList = GetNode<UIButton>("%CloseRobotList");
        closeRobotList.Pressed += HideRobotList;
        levelRobotList = GetNode<VBoxContainer>("%LevelRobotList");
    }

    public void HideRobotList()
    {
        robotList.Visible = false;
    }

    public void ShowRobotList(List<Robot> robots, string info)
    {
        listInfoLabel.Text = info;
        var children = levelRobotList.GetChildren();
        var count = children.Count;
        var diff = robots.Count - count;

        int i = 0;
        foreach (LevelRobotListItem c in children.Cast<LevelRobotListItem>())
        {
            if (i < robots.Count)
            {
                c.Init(robots[i]);
                i++;

            }
            else
            {
                c.Hide();
            }
        }
        if (diff > 0)
        {
            for (int j = 0; j < diff; j++)
            {
                var item = robotItemPrefab.Instantiate<LevelRobotListItem>();
                levelRobotList.AddChild(item);
                item.Init(robots[i]);
                item.OnRobotItemPressed += OnRobotItemPressedHandler;
                i++;
            }
        }
        robotList.Show();
    }

    private void OnRobotItemPressedHandler(Robot robot)
    {
        EmitSignal(SignalName.OnRobotListItemPressed, robot);
    }


    private void ShowPlayerRobotListHandler()
    {
        ShowRobotList(rmg.PlayerRobots, "玩家队伍");
    }


    private void ShowEnemyRobotListHandler()
    {
        ShowRobotList(rmg.EnemyRobots, "敌方队伍");
    }


    private void OnButtonPressedHandler(UIButton button)
    {
        var cmd = Enum.Parse<LevelMenuCommnad>(button.CommandString);
        if (cmd == LevelMenuCommnad.BackLevel)
        {
            AnimateHide();
        }
        else
        {
            EmitSignal(SignalName.OnMenuButtonCommand, button.CommandString);
        }
    }


    Tween tween;
    Vector2 startPos = new Vector2(0, 648);
    Vector2 endPos = new Vector2(0, 0);
    private void LevelMenuPressedHandler()
    {
        if (levelManager.CurrentCommand != RobotUICommand.None) return;
        AnimateShow();
    }

    public void AnimateShow()
    {
        tween?.Stop();
        tween = CreateTween();
        tween.TweenProperty(MenuRoot, "position", endPos, 0.2f);
        tween.Finished += OnTweenFinishedHandler;
    }

    private void OnTweenFinishedHandler()
    {
        EmitSignal(SignalName.OnMenuAnimated);
    }

    public void AnimateHide()
    {
        tween?.Stop();
        tween = CreateTween();
        tween.TweenProperty(MenuRoot, "position", startPos, 0.2f);
        tween.Finished += OnTweenFinishedHandler;
    }

    public override void _Ready()
    {
        base._Ready();
        GetChildComponents();
    }

    internal void RefreshUI()
    {
        gameRound.Text = levelManager.CurrentRoundIndex.ToString();
        redNum.Text = rmg.EnemyRobots.Count.ToString();
        blueNum.Text = rmg.PlayerRobots.Count.ToString();
    }

    public void WarningMessage(string msg)
    {
        var node = message.Instantiate<MessageWarning>();
        messageRoot.AddChild(node);
        node.ShowMessage(msg);
    }
}
